package com.guo.mixframe.framework.session

import com.guo.mixframe.framework.utils.StringHelper
import java.util.concurrent.ConcurrentHashMap

/**
 * @author  gx
 * @description
 */
class SessionManager{

  companion object{
    private val instance : SessionManager

    @JvmStatic
    fun getInstance():SessionManager{
        return SessionManager()
    }


    init {
      this.instance = SessionManager.getInstance()
    }

    val sessionMap = ConcurrentHashMap<String, SessionObject>()

    val userSessionMap = ConcurrentHashMap<String,String>()
  }



  /**
   * 通过sessionId取SessionObject
   */
  fun check(session: String?): SessionObject? {
    if (StringHelper.isNullOrEmpty(session)) return null
    synchronized(this) { return sessionMap[session] }
  }


  fun checkByPlayerId(playerId:String): SessionObject? {
    if(StringHelper.isNullOrEmpty(playerId)){
      return null
    }
    val session: String? = userSessionMap[playerId]
    return sessionMap[session]
  }

  fun updateSession(sessionObject: SessionObject) : SessionObject? {
    if(StringHelper.isNullOrEmpty(sessionObject.session)){
      return null
    }
    val oldSession = userSessionMap[sessionObject.playerId]
    if(oldSession != null){
      sessionMap.remove(oldSession)
    }
    userSessionMap[sessionObject.playerId!!] = sessionObject.session!!
    return sessionObject
  }


  public fun removeByPlayer(playerId: String) {
    if(StringHelper.isNullOrEmpty(playerId)){
        return
    }
    val session = userSessionMap[playerId]
    if(session != null){
      sessionMap.remove(session)
    }
    userSessionMap.remove(playerId)
  }


  /**
   * 清理所有session
   */
  fun removeAll() {
      sessionMap.clear()
      userSessionMap.clear()
  }

  /**
   * 取所有session
   */
  fun getAllSession(): MutableCollection<SessionObject> {
    return sessionMap.values
  }


}
